const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql2');
const rolesController = require('./rolesController'); // 引入角色控制器

const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());



// 创建 MySQL 连接
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password', // 替换为你的 MySQL 密码
  database: 'your_database_name' // 替换为你的数据库名称
});

// 连接到数据库
connection.connect(error => {
  if (error) {
    console.error('Unable to connect to the database:', error);
    return;
  }
  console.log('Connected to the database');
});

// 设置中间件
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// 设定路由

// 创建用户
// 创建角色
app.post('/roles', async (req, res) => {
  const { role_name, description } = req.body;
  try {
    await rolesController.createRole(role_name, description);
    res.status(201).send('Role created successfully');
  } catch (error) {
    console.error('Error creating role:', error);
    res.status(500).send('Error creating role');
  }
});

// 获取所有角色
app.get('/roles', async (req, res) => {
  try {
    const roles = await rolesController.getAllRoles();
    res.json(roles);
  } catch (error) {
    console.error('Error getting roles:', error);
    res.status(500).send('Error getting roles');
  }
});

// 更新角色
app.put('/roles/:id', async (req, res) => {
  const { role_name, description } = req.body;
  const roleId = req.params.id;
  try {
    await rolesController.updateRole(roleId, role_name, description);
    res.send('Role updated successfully');
  } catch (error) {
    console.error('Error updating role:', error);
    res.status(500).send('Error updating role');
  }
});

// 删除角色
app.delete('/roles/:id', async (req, res) => {
  const roleId = req.params.id;
  try {
    await rolesController.deleteRole(roleId);
    res.send('Role deleted successfully');
  } catch (error) {
    console.error('Error deleting role:', error);
    res.status(500).send('Error deleting role');
  }
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});